package com.sbtr.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * md5信息摘要生成工具类
 * @author oujh5
 *
 */
public class Md5Util {
	private Md5Util() {}
	private static Logger logger = LoggerFactory.getLogger(Md5Util.class);
	private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
	'f' };
	/**
	 * 生成md5信息摘要
	 * @param source
	 * @return
	 */
	public static String md5(String source){
		
		if(StringUtils.isNotEmpty(source)){
	        try {
	            MessageDigest md5 = MessageDigest.getInstance("MD5");
	            md5.update(source.getBytes());
	            byte[] md5Bytes = md5.digest();                     //计算md5摘要
	            
	            //编码成base64编码输出
	            Base64.Encoder encoder = Base64.getEncoder();
	            return encoder.encodeToString(md5Bytes);
	        } catch (NoSuchAlgorithmException e) {
	            logger.error("生成md5信息摘要异常", e);
	        }
		}
        return null;
    }
	
	public static String digest(String message) {
		if (message == null || "".equals(message)) {
			return "";
		}
		try {
			byte[] strTemp = message.getBytes("UTF-8");
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char[] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
  }
 }
}
